import { defineStore, acceptHMRUpdate } from 'pinia'
import Storage from '@/utils/Storage'
import { TOKEN_KEY } from '@/utils/constant'
import { usePermissionStore } from '@/store'
import { login as loginApi, logout as logoutApi, type LoginData } from '@/api/auth'
import { getUserBaseData, type UserInfo } from '@/api/system/user'
import { aesEncryptECB } from '@/utils/crypto'
import { useStorage } from '@vueuse/core'

export const useUserStore = defineStore('user', () => {
  const userInfo = useStorage<UserInfo>('userInfo', {} as UserInfo)

  async function login(loginData: LoginData) {
    const { username, password } = loginData
    const fullPassword = `${password}#${Date.now()}`
    const key = 'SZSCjDcHtlnrYPzD'
    const aesPassword = aesEncryptECB(fullPassword, key)
    return new Promise<void>((resolve, reject) => {
      loginApi({ username, password: aesPassword })
        .then(data => {
          const { access_token } = data.result
          Storage.setStorage(TOKEN_KEY, access_token)
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  }

  /**
   * 获取用户信息
   */
  function getUserInfo() {
    return new Promise<ResponseData<UserInfo>>((resolve, reject) => {
      getUserBaseData()
        .then(data => {
          Object.assign(userInfo.value, { ...data.result })
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  }

  /**
   * 登出
   */
  function logout() {
    return new Promise<void>((resolve, reject) => {
      logoutApi()
        .then(() => {
          clearUserSession()
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  }

  /**
   * 更新用户信息
   */
  function updateUserInfo(data: UserInfo) {
    Object.assign(userInfo.value, { ...data })
  }

  /**
   *  清理用户会话
   */
  function clearUserSession() {
    const permission = usePermissionStore()
    return new Promise<void>(resolve => {
      Storage.remove(TOKEN_KEY)
      permission.resetRouter()
      resolve()
    })
  }

  return {
    userInfo,
    getUserInfo,
    updateUserInfo,
    login,
    logout,
    clearUserSession
  }
})

if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useUserStore, import.meta.hot))
}
